<?php
namespace app\agent\controller;

use think\Db;
use think\Request;

class Salesman extends  Base
{
    public function index(){
        $get['name']=isset($_GET['name'])?$_GET['name']:'';
        $get['p']=isset($_GET['p'])?$_GET['p']:config('paginate.list_rows');
        if(empty($_GET)){
            $list = Db::name('salesman')
                ->where('aid',session('agents.id'))
                ->order('id desc')
                ->paginate(10);
        }else{
            $list = Db::name('salesman')
                ->where('aid',session('agents.id'))
                ->where('yname','like',"%{$get['name']}%")
                ->paginate(10,false,['query'=>$get]);
        }
        $type = Db::name('salesman_type')
            ->where(['aid'=>session('agents.id'),'vid'=>3])
            ->select();
        $name = [];
        foreach ($type as $k=>$v){
            $name[$v['id']] = $v['typename'];
        }
        $page = $list->render();
        return view('salesman/index',['list'=>$list,'page'=>$page,'get'=>$get,'name'=>$name]);

    }

    public function add(){
        if(empty($_POST)){
            $type = Db::name('salesman_type')->where(['aid'=>session('agents.id'),'state'=>1])->field('typename,id')->select();
            if($type){
                return view('salesman/add',['type'=>$type]);
            }else{
                return "<script>alert('必须先设置部门');window.location.href = '/agent/Salesmantype/index';</script>";
            }
        }else{
            $param = myarr($this->request->post());
            if($param['password']!=$param['repassword']) return "<script>alert('密码不一致');history.go(-1);</script>";
            if($param['post']==null) return "<script>alert('部门必须设置');history.go(-1);</script>";
            if(preg_match('/(^1[3|4|5|6|7|8|9]\d{9}$)|(^09\d{8}$)/', $param['phonenumber'])!= 1) return "<script>alert('手机号格式错误');history.go(-1);</script>";
            $aid = session('agents.id');
            $ywy = DB::name('salesman')->where(['phonenumber'=>$param['phonenumber']])->find();
            if($ywy) return "<script>alert('添加失败,该手机已经被注册');history.go(-1);</script>";
            $data = [
                'aid'=>session('agents.id'),
                'vid'=> 3,
                'yname'=>$param['name'],
                'phonenumber'=>$param['phonenumber'],
                'post'=>$param['post'],
                'password'=>Md5('ywy'.$param['password']),
                'entryTime'=>date('Y-m-d H:i:s'),
                'state'=>$param['state'],
            ];
            $in = Db::name('salesman')->insertGetId($data);
            $datas = [
                'wid'=>session('agents.id'),
                'logintoip' => $_SERVER['REMOTE_ADDR'],
                'logintime' => date('Y-m-d H:i:s'),
                'operation' => '新增业务员：ID:'.$in.'/'.$param['name'],
                'va'=>2,//代理商
            ];
            Db::name('login_va')->insert($datas);
            if($in){
                return "<script>alert('新增成功');parent.location.reload();</script>";
            }else{
                return "<script>alert('添加失败');history.go(-1);</script>";
            }
        }
    }

    public function state(){
        $ywy = Db::name('salesman')->where(['id'=>$_GET['id'],'aid'=>session('agents.id'),'vid'=>3])->find();
        if($ywy['state']==3) return "<script>alert('已离职无法修改');window.location.href = document.referrer;</script>";
        if($ywy['state']==1){
            $up = Db::name('salesman')->where('id',$ywy['id'])->update(['state'=>2]);
            if($up){
                return "<script>window.location.href = document.referrer;</script>";
            }else{
                return "<script>window.location.href = document.referrer;</script>";
            }
        }elseif($ywy){
            $up = Db::name('salesman')->where('id',$ywy['id'])->update(['state'=>1]);
            if($up){
                return "<script>window.location.href = document.referrer;</script>";
            }else{
                return "<script>window.location.href = document.referrer;</script>";
            }
        }
    }


    //xg
    public function edit(){
        if(empty($_POST)){
            $list = Db::name('salesman')->where(['id'=>$_GET['id'],'aid'=>session('agents.id'),'vid'=>3])->find();
            $type = Db::name('salesman_type')->where(['aid'=>session('agents.id'),'vid'=>3])->select();
            if($list['state']==3) return "<script>alert('该业务员已经离职无法修改');history.go(-1);</script>";
            return view('salesman/edit',['list'=>$list,'type'=>$type]);
        }else{
            $param = myarr($this->request->post());
            $aid = session('agents.id');
            if($param['state']==3){
                $user = Db::name('users')->where(['aid'=>session('agents.id'),'yid'=>$param['id']])->find();
                if($user) return "<script>alert('请先取消该业务员下面所以的客户才能设置为离职');parent.location.reload();</script>";
                //离职
                $up = Db::name('salesman')->where(['id'=>$param['id'],'aid'=>$aid,'vid'=>3])->update(['state'=>3,'quitTime'=>date('Y-m-d H:i:s')]);
                if($up){

                    $data = [
                        'wid'=>$aid,
                        'logintoip' => $_SERVER['REMOTE_ADDR'],
                        'logintime' => date('Y-m-d H:i:s'),
                        'operation' => '业务员ID:'.$param['id'].'离职',
                        'va'=>2,//代理商
                    ];
                    Db::name('login_va')->insert($data);

                    return "<script>alert('修改成功');parent.location.reload();</script>";
                }
            }else {
                $ywy = DB::name('salesman')->where(['id' => $param['id'],'aid'=>$aid,'vid'=>3])->find();
                if($param['password']!=null){
                    if ($param['password'] != $param['repassword']) return "<script>alert('密码不一致');history.go(-1);</script>";
                    $pwd = Md5('ywy'.$param['password']);
                }else{
                    $pwd = $ywy['password'];
                }

                $datas = [
                    'wid'=>$aid,
                    'logintoip' => $_SERVER['REMOTE_ADDR'],
                    'logintime' => date('Y-m-d H:i:s'),
                    'va'=>2,//代理商
                ];

                if($ywy['phonenumber']!=$param['phonenumber']){
                    if (preg_match('/(^1[3|4|5|6|7|8|9]\d{9}$)|(^09\d{8}$)/', $param['phonenumber']) != 1) return "<script>alert('手机号格式错误');history.go(-1);</script>";
                    $phone = DB::name('salesman')->where(['phonenumber' => $param['phonenumber'],'aid'=>session('agents.id'),'vid'=>3])->find();
                    if ($phone&&$phone['aid']==$aid) return "<script>alert('添加失败,该手机已经被注册');history.go(-1);</script>";
                    $phonenumber = $param['phonenumber'];

                    $datas['operation'] = '修改业务员手机号：原：'.$ywy['phonenumber'].'/'.'现：'.$param['phonenumber'];

                }else{
                    $phonenumber = $ywy['phonenumber'];
                    $datas['operation'] = '修改业务员信息';
                }
                $data = [
                    'yname' => $param['name'],
                    'phonenumber' => $phonenumber,
                    'post' => $param['post'],
                    'password' => $pwd,
                    'state' => $param['state'],
                ];
                $up = Db::name('salesman')->where(['id'=>$param['id'],'aid'=>session('agents.id'),'vid'=>3])->update($data);
                if ($up) {

                    Db::name('login_va')->insert($datas);

                    return "<script>alert('修改成功');parent.location.reload();</script>";
                }else{
                    return "<script>alert('修改失败，提交信息未改变');parent.location.reload();</script>";
                }
            }
        }
    }

    public function user(){
        $get['name']=isset($_GET['name'])?$_GET['name']:'';
        $get['p']=isset($get['p'])?$get['p']:config('paginate.list_rows');
        $aid = session('agents.id');
        $salesman = Db::name('salesman')->where(['aid'=>session('agents.id'),'id'=>$_GET['id'],'vid'=>3])->find();
        if($salesman['state']==3) return "<script>alert('该业务员已经离职无法添加');history.go(-1);</script>";
        if(empty($_GET['name'])){
            $list = Db::name('users')->where(['aid'=>$aid,'yid'=>$_GET['id']])->paginate(15,false,['query'=>$_GET]);
            $count = Db::name('users')->where(['aid'=>$aid,'yid'=>$_GET['id']])->count();
        }else{
            $list = Db::name('users')
                ->where(['aid'=>$aid,'yid'=>$_GET['id'],'vid'=>3])
                ->where('name|phonenumber','like',"%{$_GET['name']}%")
                ->paginate(15,false,['query'=>$_GET]);
            $count = Db::name('users')->where(['aid'=>$aid,'yid'=>$_GET['id'],'vid'=>3])->where('name|phonenumber','like',"%{$_GET['name']}%")->count();
        }
        $page = $list->render();
        return view('salesman/userlist',['list'=>$list,'get'=>$get,'page'=>$page,'salesman'=>$salesman,'count'=>$count]);
    }

    public function useradd(){
        if(empty($_POST)){
            $user = Db::name('users')->where(['aid'=>session('agents.id'),'yid'=>null])->select();
            $ywy = Db::name('salesman')->where('id',$_GET['id'])->find();
            $count = count($user);
            return view('salesman/useradd',['user'=>$user,'count'=>$count,'ywy'=>$ywy]);
        }else{
            $param = $this->request->post();
            for($i=0;$i<count($param['userId']);$i++){
                $user = Db::name('users')->where(['id'=>$param['userId'][$i],'aid'=>session('agents.id')])->find();
                if($user['yid']==null){
                    $up = Db::name('users')->where('id',$user['id'])->update(['yid'=>$param['yid']]);
                }
            }
         return "<script>alert('添加成功');parent.location.reload();</script>";
        }
    }

    //yichu
    public function yichu(){;
        $yi = Db::name('users')->where(['aid'=>session('agents.id'),'id'=>$_GET['id']])->find();
        $up = Db::name('users')->where('id',$yi['id'])->update(['yid'=>null]);
        if($up){
            $data = [
                'wid'=>session('agents.id'),
                'logintoip' => $_SERVER['REMOTE_ADDR'],
                'logintime' => date('Y-m-d H:i:s'),
                'operation' => '移除终端用户ID:'.$_GET['id'].'的业务员ID:'.$yi['yid'],
                'va'=>2,//代理商
            ];
            Db::name('login_va')->insert($data);
            return "<script>alert('移除成功');window.location.href = document.referrer;</script>";
        }
    }

    public function addsalesman(){
        $aid = session('agents.id');
        if(empty($_POST)){
            $yname = Db::name('salesman')->where(['aid'=> $aid,'state'=>1,'vid'=>3])->select();
            return view('salesman/addsalesman',['yname'=>$yname]);
        }else{
            $yname = Db::name('salesman')->where(['aid'=>$aid,'id'=>$_POST['yid'],'vid'=>3])->find();
            if($yname){
                $up = Db::name('users')->where(['aid'=> $aid,'id'=>$_POST['userId']])->update(['yid'=>$_POST['yid']]);
                if($up){

                    $data = [
                        'wid'=>session('agents.id'),
                        'logintoip' => $_SERVER['REMOTE_ADDR'],
                        'logintime' => date('Y-m-d H:i:s'),
                        'operation' => '终端用户ID:'.$_POST['userId'].'新增业务员ID:'.$_POST['yid'],
                        'va'=>2,//代理商
                    ];
                    Db::name('login_va')->insert($data);

                    return "<script>alert('添加成功');parent.location.reload();</script>";
                }else{
                    return "<script>alert('添加失败');parent.location.reload();</script>";
                }
            }else{
                return "<script>alert('修改失败');parent.location.reload();</script>";
            }
        }
    }

    public function editsalesman(){
        $aid = session('agents.id');
        if(empty($_POST)){
            $yname = Db::name('salesman')->where(['aid'=> $aid,'state'=>1,'vid'=>3])->select();
            $user = Db::name('users')->where(['id'=>$_GET['id']])->find()['yid'];
            return view('salesman/editsalesman',['user'=>$user,'yname'=>$yname]);
        }else{
//            dump($_POST);
            $yname = Db::name('salesman')->where(['aid'=>session('agents.id'),'id'=>$_POST['yid'],'state'=>1,'vid'=>3])->find();
            if($yname){
                $yid = Db::name('users')->where(['aid'=> $aid,'id'=>$_POST['userId']])->find()['yid'];
                $up = Db::name('users')->where(['aid'=> $aid,'id'=>$_POST['userId']])->update(['yid'=>$_POST['yid']]);
                if($up){
                    $data = [
                        'wid'=>session('agents.id'),
                        'logintoip' => $_SERVER['REMOTE_ADDR'],
                        'logintime' => date('Y-m-d H:i:s'),
                        'operation' => '终端用户ID:'.$_POST['userId'].'修改业务员现ID:'.$_POST['yid'].'/原:'.$yid,
                        'va'=>2,//代理商
                    ];
                    Db::name('login_va')->insert($data);

                    return "<script>alert('修改成功');parent.location.reload();</script>";
                }else{
                    return "<script>alert('修改失败，修改信息和原信息相同');parent.location.reload();</script>";
                }
            }else{
                return "<script>alert('修改失败');parent.location.reload();</script>";
            }
        }
    }


}
